﻿﻿package com.glidecast.controllers
{
	import flash.net.URLRequest;
	import flash.net.URLLoader;
	import flash.net.URLVariables;
	import flash.events.EventDispatcher;

	import flash.display.Bitmap;

	import com.glidecast.models.RSSItem;
	
	import flash.events.Event;
	import flash.events.EventDispatcher;
	
	public class RSSItemController  extends EventDispatcher
	{
		private var ldr:URLLoader=new URLLoader;
		public static var COMPLETE:String='RSSItemDownloadComplete';
		
		public function RSSItemController()
		{	
		}
		private var _rssitem:RSSItem;
		public function get rssitem():RSSItem
		{
			return _rssitem;
		}
		public function set rssitem(s:RSSItem):void
		{
			_rssitem=s;
		}
		public function load():void
		{	
			if (this.rssitem == null)
				return;
			if (this.rssitem.enclosureurl == null)
				return;	
			if (this.rssitem.enclosureurl == '')
				return;	
			try
			{			
				var urlReq:URLRequest = new URLRequest(this._rssitem.enclosureurl);
				ldr.addEventListener("complete", enclosureLoaded);
				ldr.load(urlReq);
			}
			catch(error:Error)
			{
				trace("RSSItemController load error: " + error);
			}
		}
		public function enclosureLoaded(event:Event):void 
		{
			try
			{
				//security issue? bail.
				var loader:URLLoader = URLLoader(event.target);
				//if its not an image, bail.
				var image:Bitmap= loader.data as Bitmap;
				this._rssitem.enclosure = image;
			
				dispatchEvent(new Event(RSSItemController.COMPLETE));			
				trace("Loaded RSSItem enclosure ");
			}
			catch(error:Error)
			{
				trace("enclosureLoaded error: " + error);
			}
		}
		
	}
}
